package com.zhou.essearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhou.essearch.document.DocDocument;
import com.zhou.essearch.repository.DocDocumentRepository;
import com.zhou.essearch.service.EsSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * elasticsearch 搜索引擎 service实现
 * @author jiangshicun
 * @version 0.1
 * @date 2020/01/13 15:33
 */
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl<DocDocument> implements EsSearchService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;
    @Resource
    private DocDocumentRepository DocDocumentRepository;

    @Override
    public void save(DocDocument ... DocDocuments) {
        elasticsearchTemplate.putMapping(DocDocument.class);
        if(DocDocuments.length > 0){
            /*Arrays.asList(DocDocuments).parallelStream()
                    .map(DocDocumentRepository::save)
                    .forEach(DocDocument -> log.info("【保存数据】：{}", JSON.toJSONString(DocDocument)));*/
            log.info("【保存索引】：{}",JSON.toJSONString(DocDocumentRepository.saveAll(Arrays.asList(DocDocuments))));
        }
    }

    @Override
    public void delete(String id) {
        DocDocumentRepository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        DocDocumentRepository.deleteAll();
    }

    @Override
    public DocDocument getById(String id) {
        DocDocument docDocument = null;
        try {
            docDocument = DocDocumentRepository.findById(id).get();
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return docDocument;
    }

    @Override
    public List<DocDocument> getAll() {
        List<DocDocument> list = new ArrayList<>();
        DocDocumentRepository.findAll().forEach(list::add);
        return list;
    }

}
